export default {
	//给当前的模块开启一个命名空间
	namespaced: true,
	
	//存放购物车数据
	state: () => ({
		cart:JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	//用来写方法的 是唯一一个可以改变我们的 state 状态的
	mutations: {
		//获取商品信息加入购物车
		addToCart(state, goods){
			const findResult = state.cart.find((x) => x.goods_id === goods.goods_id)
			if(!findResult) {
				state.cart.push(goods)
			} else {
				findResult.goods_count ++
			}
			//通过commit方法调用 my_cart 命名空间下的saveToStorage 方法
			this.commit('myCart/saveToStorage')
		},
		saveToStorage(state){
			uni.setStorageSync('cart',JSON.stringify(state.cart))
		},
		radioClickChange(state,goods){
			const findResult = state.cart.find((x) => x.goods_id === goods.goods_id)
			
			if(findResult){
				findResult.goods_state = goods.goods_state
				this.commit('myCart/saveToStorage')
			}
		},
		numClickChange(state,goods) {
			const findResult = state.cart.find((x) => x.goods_id === goods.goods_id)
			
			if(findResult){
				findResult.goods_count = goods.goods_count
				this.commit('myCart/saveToStorage')
			}
		},
		removerGoodsCartItem(state,goods_id){
			state.cart = state.cart.filter(x =>x.goods_id !== goods_id)
			this.commit('myCart/saveToStorage')
		},
		// 更新所有商品的勾选状态
		updateAllGoodsState(state,newState){
			state.cart.forEach(x =>x.goods_state = newState)
			// 储存
			this.commit('myCart/saveToStorage')
		}
		
	},
	//计算属性
	getters:{
		// 购物车中所有商品的数量
		total(state){
			// let c = 0
			// state.cart.forEach(goods => c += goods.goods_count)
			// return c
			return state.cart.reduce((total,item) => total+=item.goods_count,0)
		},
		// 勾选商品的总数量
		checkedCount(state){
			// 过滤勾选状态
			return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total +=item.goods_count,0)
		},
		// 已勾选商品的总价格
		checkedGoodsAmount(state){
			return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total += item.goods_count*item.goods_price,0).toFixed(2)
		}
	},
	//用来写异步  请求数据
	actions:{}
}